﻿CREATE PROCEDURE [dbo].[proc_Order_Update]
(
		@OId uniqueidentifier
		,@CusId	uniqueidentifier
		,@CusName	nvarchar(50)
,@CusName_BD	nvarchar(50)
		,@CusPerson	nvarchar(50)
		,@CusPersonTel	nvarchar(50)
		,@CusDescription	nvarchar(1000)
		,@CusEstimate	nvarchar(200)
		,@TypeId	int
		,@TypeName	nvarchar(50)
		,@WayId	int
		,@WayName	nvarchar(50)
		,@ProcessId	int
		,@ProcessName	nvarchar(50)
		,@TradeDate	datetime
		,@CreateDate datetime
	,@shjbh	nvarchar(50)
	,@htbh nvarchar(50)
		,@YingShouPrice	decimal(18, 2)
		,@ShiShouPrice decimal(18, 2)
		,@Discount	nvarchar(50)
		,@PaymentTypeId	int
		,@PaymentType	nvarchar(50)
		,@BankId int
		,@Bank	nvarchar(50)
		,@PaymentDescription	nvarchar(200)
		,@OtherDescription	nvarchar(1000)
		,@SalesmanAccount nvarchar(50)
	)
AS
Begin Tran
	Declare @nCount int, @tmpSumJe decimal(18, 2)
	Set @nCount = 0		--初始化变量
	Select @nCount=Count(0),@tmpSumJe=Sum(UnitPrice*Quantity) From Order_Item Where Occupancy=@SalesmanAccount Or OId=@OId
	If @nCount = 0	--缺少成单项
		Begin
			RollBack Tran
			Return -6
		End

	If @tmpSumJe <> @YingShouPrice	--成单项之和与应收不符
		Begin
			RollBack Tran
			Return -2
		End

	Update [Order] Set
			CusId=@CusId
			,CusName=@CusName
			,CusPerson=@CusPerson
			,CusPersonTel=@CusPersonTel
			,CusDescription=@CusDescription
			,CusEstimate=@CusEstimate
			,TypeId=@TypeId
			,TypeName=@TypeName
			,WayId=@WayId
			,WayName=@WayName
			,ProcessId=@ProcessId
			,ProcessName=@ProcessName
			,TradeDate=@TradeDate
			,CreateDate=@CreateDate
		,shjbh=@shjbh
		,htbh=@htbh
			,YingShouPrice=@YingShouPrice
			,ShiShouPrice=@ShiShouPrice
			,Discount=@Discount
			,PaymentTypeId=@PaymentTypeId
			,PaymentType=@PaymentType
			,BankId=@BankId
			,Bank=@Bank
			,PaymentDescription=@PaymentDescription
			,OtherDescription=@OtherDescription
			,StateId=-1		-- -1为等待部门主管审核
			,F_YingShou=@YingShouPrice	--审批前修改(=首次录入)时的成单总额，财报统计专用(2012-09-22)
	Where OId=@OId
	
	Update Order_PaymentRecord Set CreateDate=@CreateDate
			,Prices=@ShiShouPrice
			,PaymentTypeId=@PaymentTypeId
			,PaymentType=@PaymentType
			,BankId=@BankId
			,Bank=@Bank
	Where OId=@OId And SWName='首款'

	Update Order_Item Set OId=@OId,Occupancy=NULL,CreateDate=Getdate(),TradeDate=@TradeDate Where Occupancy=@SalesmanAccount
	Update Customer Set StateId=2,ProtectId=3,ProtectName=NULL,ProtectDate=NULL Where CustomerId=@CusId

	If @@error <> 0  --发生错误
		Begin
			RollBack Tran
			Return 0
		End
	Else
		Begin
			Commit Tran
			Return 1    --执行成功
End